﻿package com.cilico.single.components;

import java.net.URLDecoder;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.cilico.single.ConfigManager;
import com.cilico.single.utils.StringTicker;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.FormLayout;

/**
 * Label控件
 * 
 * @author lv.xiangan
 *
 */
public class Label extends TextView implements Component {
	private static final int MAXLENGTH = Component.MAX_ROW_WIDTH - 10;
	public CssStyle cssStyle_;
	public CssStyle pseudoStyle_;
	public int offsetLength = 20;
	TextPaint labelFont_;
	private String[] label_;
	public boolean isHyperLink_;
	public String linkAddr_;
	public boolean focus_;
	private BaseView bv_;

	// just use for parse.
	public boolean isTagParse_ = false;

	/**
	 * Indicator of setting label and text in ONE row.
	 */
	private boolean isLabelIndianFile_;

	/**
	 * when it is true, its attrName_/attrValue_ will be use to transfer
	 * parameters to the server
	 */
	public boolean isValueLabel_ = false;

	// Roll always without no stopping
	public boolean isRollNotStop;

	/** the position of the nubmer */
	public String offset_;
	/** delay time */
	public int delaytime_;
	public int textColor_;
	/** count down */
	boolean isCountDown_;
	String[] relaDismiss_;
	String[] relaUnfocusable_;
	/** for test */
	public String caption_;
	public String attrName_;
	public String attrValue_;
	public String labelName_;
	public String isEncrypt_;

	int left_; // Relative left position to the left of the FULL canvas.
	int top_; // Relative left position to the top of the FULL canvas.
	int width_;
	int height_;
	int cssWidth_;
	
	protected boolean isClicked_ = false;
	protected int clickedColor_;
	private int marginBottom_;
	private int marginTop_;
	private LinearLayout selfLayout_;
	private boolean isInTable_;
	private FormLayout formLayout_;
	ArrayList<String> strArray;
	String strikethrough_;
	
	public Label(Context context, String text, boolean isHyperLink, boolean isSingleLine, boolean isFocusable) {
		super(context);
		bv_ = (BaseView) context;
		this.setSingleLine(isSingleLine);
		this.setFocusable(isFocusable);
		this.setFocusableInTouchMode(isFocusable);
		this.setMinHeight(ConfigManager.SIZE_SMALL + 4);
		// 设置该控件文字颜色
		this.setTextColor(BaseView.FOREGROUND_COLOR);
		labelFont_ = getPaint();
		if (isFocusable) {
			labelName_ = text;
		}
		// 设置显示内容
		setContentText(text);
		isRollNotStop = false;
	}

	public Label(Context context, String text, boolean isFocusable) {
		super(context);
		bv_ = (BaseView) context;
		setFocusable(isFocusable);
		this.setFocusableInTouchMode(isFocusable);
		this.setMinHeight(ConfigManager.SIZE_SMALL + 4);
		setContentText(text);
		isRollNotStop = false;
		// 设置该控件文字颜色
		this.setTextColor(BaseView.FOREGROUND_COLOR);
		labelFont_ = getPaint();
		if (isFocusable) {
			labelName_ = text;
		}
		labelFont_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
	}

	public Label(Context context) {
		super(context);
		bv_ = (BaseView) context;
		// 设置该控件文字颜色
		this.setTextColor(BaseView.FOREGROUND_COLOR);
		labelFont_ = getPaint();
		labelFont_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
		isRollNotStop = false;
	}

	public String getContentText() {
		return super.getText().toString();
	}

	public void setContentText(String text) {
		String labelText;
		try {
			labelText = URLDecoder.decode(text);
        } catch (IllegalArgumentException e) {
        	labelText = text;
        }
        //替换所有的字表符
        labelText = labelText.replace("	", "  ");
        if (labelText.contains("^2b^")) {
        	labelText = labelText.replace("^2b^", "%");
        }
		setText(labelText);
	}

	protected void calculateHeight() {
		height_ = (int) (this.getLineCount() * this.getLineHeight() + marginTop_ + marginBottom_);
		if (label_ == null) {
			return;
		}
		if (isLabelIndianFile_) {
			height_ = (int) Math.max(height_, labelFont_.getTextSize());
		} else {
			height_ += labelFont_.getTextSize() * label_.length;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		boolean isAction = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			bv_.currentItem_ = bv_.tabBar_.indexOfContentChild(this);
			isAction = pointerPressed(bv_);
			break;
		default:
			isAction = super.onKeyDown(keyCode, event);
		}
		return isAction;
	}

	public boolean onTouchEvent(MotionEvent event) {
		boolean isAction = false;
		int touchEvent = event.getAction();
		int x = (int) event.getX();
		int scrollX = 0;
		int touchDownX = 0;
		int move = 0;
		switch (touchEvent) {
		case MotionEvent.ACTION_DOWN:
			if (isRollNotStop)
				isRollNotStop = false;
			else if (labelFont_.measureText(this.getText().toString()) >= MAXLENGTH)
				isRollNotStop = true;
			scrollX = getScrollX();
			touchDownX = (int) event.getX();
			this.requestFocus();
			this.invalidate();
			isAction = pointerPressed(bv_);
			break;
		case MotionEvent.ACTION_MOVE:
			BaseView.setTypeFace(labelFont_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			if (null != this.getContentText()) {
				final int tempWidth = (int) (labelFont_.measureText(this.getContentText().toString()) + 5);
				if (tempWidth > width_) {
					// 修正用于移动的触摸x坐标
					x += scrollX - getScrollX();
					if ((x - touchDownX) > 0) {
						// 向右拖動
						move = (x - touchDownX) > scrollX ? 0 : (scrollX - x + touchDownX);
						scrollTo(move, 0);
					} else {
						// 向左拖動
						if (tempWidth > width_ + scrollX - BaseView.DEFAULT_VIEW_TOP_MARGIN) {
							move = (touchDownX - x) > (tempWidth - width_ - scrollX + BaseView.DEFAULT_VIEW_TOP_MARGIN) ? (tempWidth - width_ + BaseView.DEFAULT_VIEW_TOP_MARGIN) : (touchDownX - x + scrollX);
							scrollTo(move, 0);
						}
					}
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			bv_.currentItem_ = bv_.tabBar_.indexOfContentChild(this);
			isAction = pointerPressed(bv_);
			break;
		default:
			isAction = super.onTouchEvent(event);
		}

		return isAction;
	}

	/**
	 * 绘制除二级界面的所有label
	 */
	protected void onDraw(Canvas g) {
		int bottomY = (int) (getHeight() + labelFont_.getTextSize()) >> 1;
		// 设置字体非抗锯齿效果，使字体边界更平滑
		labelFont_.setAntiAlias(true);
		labelFont_.setColor(getTextColors().getDefaultColor());
		if (isRollNotStop && this.getLineCount() < 2) {
			// 只有单行的才能滚动
			BaseView.setTypeFace(labelFont_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			StringTicker.instance().drawMoveStr(this, g, MAXLENGTH, labelFont_, getCurrentTextColor(), getContentText(), left_, bottomY);
		} else {
			if (null == this.cssStyle_) {
				this.setTextColor(Color.BLACK);
			} else {
				if (this.cssStyle_.fgColor_ == 0)
					this.setTextColor(Color.BLACK);
				else
					this.setTextColor(this.cssStyle_.fgColor_);
				if (cssStyle_.strikethrough_ > -1) {
					// 设置中划线并加清晰
					labelFont_.setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG | Paint.FAKE_BOLD_TEXT_FLAG); 
				}
			}
			setTypeface(BaseView.getTypeFace(cssStyle_ != null ? cssStyle_.fontWeight_ : null));
			if (strArray != null && strArray.size() > 0){
				float lineHeight = labelFont_.getTextSize() * 1.2f;
				if (labelFont_.isFakeBoldText()) {
					lineHeight = labelFont_.getTextSize() * 1.3f;
				}
				for (int i = 0; i < strArray.size(); i ++) {
					g.drawText(strArray.get(i), 3, lineHeight * (i + 1), labelFont_);
				}
			} else {
				super.onDraw(g);
			}
		}
	}


	/**
	 * 响应点击该按钮的执行操作
	 */
	public boolean pointerPressed(BaseView bv) {
		if (!isFocusable() || getVisibility() != View.VISIBLE)
			return false;
		boolean isAction = false;
		try {
			if (bv.listener_ != null)
				isAction = bv.listener_.componentAction(this, (BaseView) this.getContext());
		} catch (Exception ex) {
			isAction = false;
		}
		return isAction;
	}

	public void shrinkWidth() {
		// TODO Auto-generated method stub
	}

	public void cleanText() {
		// TODO Auto-generated method stub
	}

	public void setFocus(boolean isFocus, int i) {
		// TODO Auto-generated method stub
		focus_ = isFocus;
	}

	public void mould() {
		CssStyle cs = cssStyle_;
		// set the width.
		if (cs != null && cs.width_ > 0) {
			cssWidth_ = cs.width_;
			setWidth(cs.width_);
		}

		// set the height
		if (cs != null && cs.height_ > 0) {
			setHeight(cs.height_);
		}

		// set the text color.
		if (cs != null && cs.fgColor_ != 0) {
			setTextColor(cs.fgColor_);
		}
		if (cs != null && cs.right_ == 0) {
			setGravity(Gravity.RIGHT);
		}
		// set the font family (since API Level 4)
		/*
		 * String fontPath = ConfigManager.getFontPath(cbStyle.fontFamily_); if
		 * (fontPath != null) {
		 * temp.setTypeface(Typeface.createFromFile(fontPath)); }
		 */
		// set the font size.
		if (cs != null && cs.fontSize_ > 0) {
			setTextSize(cs.fontSize_);
			labelFont_.setTextSize(cs.fontSize_);
		}
		// set the background color.
		if (cs != null && cs.bgColor_ != 0) {
			setBackgroundColor(cs.bgColor_);
		}
		reSetLabelLayoutParams();
	}

	/**
	 * 重设Lable的规格参数
	 * */
	private void reSetLabelLayoutParams() {
		// 初始化控件的界面输出参数
		LinearLayout.LayoutParams viewLayout = null;
		try {
			viewLayout = (LayoutParams) getLayoutParams();
		} catch (Exception e1) {
			Utils.printException(e1);
		}

		if (null == viewLayout) {
			viewLayout = new LinearLayout.LayoutParams(getWidth(), getHeight());
		}
		String text = getContentText();
		BaseView.setTypeFace(labelFont_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		width_ = (int) (labelFont_.measureText(text) + 5);
		// we set one cell's maxWidth not bigger than the screen width. And we
		// should initialize maxWidth_ before setText().
		float adjust = 1.25f;
		if (labelFont_.isFakeBoldText()) {
			adjust = 1.35f;
		}
		if (cssWidth_ > 0) {//如果css样式定义了宽，则使用css样式的宽为最大宽
			if (width_ < cssWidth_ - 3) {
				viewLayout.width = cssWidth_;
				viewLayout.height = (int) (labelFont_.getTextSize() * adjust);
			} else {
				viewLayout.width = cssWidth_;
				// 设置label的layoutParams,实现换行
				int count = getLabelLineCount(text, cssWidth_ - 5);
				viewLayout.height = (int) (labelFont_.getTextSize() * adjust) * count + 2;
			}
		} else {
			if (width_ < Component.MAX_ROW_WIDTH - 3 - offsetLength) {
				viewLayout.width = width_ + 3;
				viewLayout.height = (int) (labelFont_.getTextSize() * adjust);
			} else {
				viewLayout.width = Component.MAX_ROW_WIDTH - offsetLength;
				// 设置label的layoutParams,实现换行
				float maxWidth = Component.MAX_ROW_WIDTH - 3 - (offsetLength > Utils.getSystemScaledValue(210) ? 0 : offsetLength);
				int count = getLabelLineCount(text, maxWidth);
				viewLayout.height = (int) (labelFont_.getTextSize() * adjust) * count + 2;
			}
		}
		
		width_ = viewLayout.width;
		if (isInTable_ && (strArray == null || strArray.size() == 1)) {
			height_ = viewLayout.height;
			height_ = Utils.getScaledValue(height_);
		} else {
			height_ = viewLayout.height;
		}
		if (selfLayout_ != null) {
			BaseView.removeViewsStepByStep(selfLayout_, this);
		}
		selfLayout_ = BaseView.createSelfLayout(bv_, viewLayout, cssStyle_, this);
		viewLayout.topMargin = -2;
		setLayoutParams(viewLayout);
	}

	int getLabelLineCount(String text, float maxWidth) {
		if (strArray == null){
			strArray = new ArrayList<String>();
		} else {
			strArray.clear();
		}
		int startIndex = 0;
		int count = 1;
		float lenght = 0;
		int strLenght = text.length();
		char hh1 = 0xa;
		char hh2 = 0xd;
		for (int i = 0; i < strLenght; i++) {
			char c = text.charAt(i);
			lenght += labelFont_.measureText(text, i, i+1);
			if (c == hh1 || c == hh2 || c == '^') {
				count ++;
				strArray.add(text.substring(startIndex, i));
				startIndex = i + 1;
				lenght = 0;
			} else if (lenght > maxWidth) {
				count++;
				strArray.add(text.substring(startIndex, i));
				startIndex = i;
				i -= 1;
				lenght = 0;
			}
		}
		if (startIndex < strLenght){
			strArray.add(text.substring(startIndex, strLenght));
		}
		return count;
	}
	

	public void removeSelfLayout() {
		if (selfLayout_ != null) {
			BaseView.removeViewsStepByStep(selfLayout_, this);
		}
		selfLayout_ = null;
	}

	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub
	}

	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub
	}

	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	public View getCmpView() {
		if (selfLayout_ != null) {
			return selfLayout_;
		}
		return this;
	}

	public int getCmpHeight() {
		return height_;
	}

	public int getCmpWidth() {
		return width_;
	}

	public void setInTable(boolean inTable) {
		isInTable_ = inTable;
	}

	public boolean isInTable() {
		return isInTable_;
	}

	public CssStyle getCssStyle() {
		return cssStyle_;
	}

	public void releaseResource(View view) {
	}

	public void setForm(FormLayout formLayout) {
		formLayout_ = formLayout;
	}

	public FormLayout getForm() {
		return formLayout_;
	}

	public void setEncrypt(String encrypt) {
		isEncrypt_ = encrypt;
	}

}
